package com.googlecode.messwertepi.gui;

import jcurses.system.CharColor;
import jcurses.system.Toolkit;
import jcurses.util.Rectangle;
import jcurses.widgets.Widget;

import java.util.StringTokenizer;

/**
 * Created by eike on 15.07.14.
 */
public class DataLabel extends Widget {
    final private static CharColor DEFAULT_TEXTCOLOR = new CharColor(CharColor.WHITE, CharColor.BLACK);

    private String text = "";

    public DataLabel(String text, CharColor textColor) {
        this.text = text;
        setColors(textColor);
    }

    public DataLabel(String text) {
        this(text, DEFAULT_TEXTCOLOR);
    }

    public void setText(String text) {
        this.text = text;
        doRepaint();
    }

    /**
     * Calculates the dimenstion of this label.
     * The height of this label will be the number of line breaks minus 1.
     * The width of this label is based on the maximum length of the lines..
     *
     * @return the dimension of this label
     */
    protected Rectangle getPreferredSize() {
        Rectangle rec = null;
        if (text.indexOf("\n") == -1) {
            rec = new Rectangle(text.length(), 1);
        } else {
            StringTokenizer tokenizer = new StringTokenizer(text, "\n");
            int width = 0;
            int height = 0;
            while (tokenizer.hasMoreElements()) {
                String token = tokenizer.nextToken();
                height++;
                if (token.length() > width) {
                    width = token.length();
                }
            }
            height = (height == 0) ? 1 : height;
            rec = new Rectangle(width, height);
        }

        return rec;
    }

    /**
     * Prints the text at the calculated position.
     */
    protected void doPaint() {
        // get the position and dimension of the text
        Rectangle rect = (Rectangle) getSize().clone();
        rect.setLocation(getAbsoluteX(), getAbsoluteY());

        // print the text
        Toolkit.printString(text, rect, getColors());
    }


    protected void doRepaint() {
        doPaint();
    }
}
